/**
 * Created by Dalyn on 2017/3/22.
 */
import React, {Component}from 'react';
import Relay from "react-relay";
import "./css/settlement.css"
import InputBox from "../../common/InputBox";
import Confirm from "../../common/Confirm";
import ExamineEnBalanceMutation from "./mutation/ExamineEnBalanceMutation";
import GetQiNiuToken from './mutation/GetQiNiuTokenMutation';
import Config from "../../util/Config"
import {Upload,message} from 'antd';
import {_Modal,_Icon,_Button} from 'ANT_DE';
const Modal= _Modal,
       Icon = _Icon,
        Button = _Button;

export default class InfoCheckBomb extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            displayflag: true,
            partyAEnid: "",
            partyBEnid: "",
            partyBEnids: "",
            maxMoney: "",
            ratio: "",
            upperLimit: "",
            loanRatio: "",
            dayRate: "",
            tranNo:"",
            tranNoHint:"",

            token:"",   //上传图片 token
            fileList:[],   //上传list
            alarm:false,  //提示
        };
        this.style = {
            confirm: {
                width: '60px',
                height: '30px',
                backgroundColor: "#1b3249",
                fontSize: "18px",
                color: "#fff",
                marginTop: "16px",
                marginLeft: "20px",
                fontFamily: "Microsoft YaHei"
            },
            upload: {
                width: '100px',
                height: '30px',
                backgroundColor: "#fff",
                fontSize: "12px",
                color: "#000",
                marginTop: "16px",
                marginLeft: "50px",
                fontFamily: "Microsoft YaHei",
                border: "1px solid #9AFF70"
            },
            upperLimit: {
                width: "120px",
                height: "22px",
                marginTop: "10px"
            },
            inputStyle:{
                width: "180px",
                height: "20px",
                marginLeft:0,
                paddingLeft:10
            }
        };
        this.isshow = 'none';
        this.isRelay = true;

        this.qiniuhref = Config.qiuniu;

        this.uploadData = this.uploadData.bind(this);
        this.fileChange = this.fileChange.bind(this);
    }

    componentWillMount() {
        //获取上传图片所需的token
        Relay.Store.commitUpdate(
            new GetQiNiuToken({}), {
                onSuccess: (res) => {
                    let errorCode = res.getQiNiuToken.getQiNiuToken.errorCode;
                    if(errorCode==0){
                        let qiniutoken = res.getQiNiuToken.getQiNiuToken.qiniutoken;
                        this.setState({
                            token:qiniutoken
                        })
                    }else if(errorCode==500){
                        message.error("服务器错误，请联系管理员")
                    }
                },
                onFailure:()=>{
                    message.error("网络请求失败 ")
                }
            }
        );
        this.createId = sessionStorage.getItem("msUid");
        this.createBy = sessionStorage.getItem("msUserName");
    }

    /*获取焦点*/
    focuson(type) {
        switch (type) {
            case "tranNo":
                this.isRelay = true;
                this.setState({
                    tranNoHint: ""
                });
                return;
        }
    }

    success(status,tranNo) {
        this.props._success(status,tranNo);
    }

    /*初始化数据*/
    initHit(){
        this.setState({
            tranNoHint: ""
        });
    }

    relayApply(){
        Relay.Store.commitUpdate(
            new ExamineEnBalanceMutation({
                orderId: this.state.orderId,
                status: this.state.status,
                remitFileJson:JSON.stringify(this.state.fileList),
                createId:this.createId,
                createBy:this.createBy
            }),
            {
                onFailure: () => {
                    console.log("请求失败");
                },
                onSuccess: (response) => {
                    let data = response.examineEnBalance.data;
                    if (data.errorCode === "0") {
                        /*请求成功-弹框隐藏*/
                        this.setState({
                            displayflag: true,
                            fileList:[],
                            alarm:false
                        }, ()=>{this.success(data.status,data.tranNo)});
                    } else {
                        this.setState({
                            tranNoHint: data.value
                        });
                    }
                }
            }
        );
    }

    /*点击确认*/
    handleConfirm(flag) {
        //是否上传完成
        if (this.isRelay) {
            if(this.state.fileList.length != 1){ this.setState({alarm:true}); return; }else if(this.state.fileList[0].status !== "done"){
                message.info("请等待文件上传完成");return;
            }
            this.setState({
                orderId: this.props._orderId,
                status: parseFloat(this.props._statusItem)+1,
            }, this.relayApply)
        }
    }

    handleCancel(flag) {
        // 是否上传完成
        this.setState({
            displayflag: !flag,
            fileList:[]
        });
    }

    beforeUpload(file){
        const MaxSize = 8;  //最大限度 8M;
        // 图片格式
        if(file.type !== "image/jpeg" && file.type !== "image/jpg" && file.type !== "image/png" && file.type !== "image/gif" && file.type !== "image/bmp"){
            message.error("图片格式错误");
            return false;
        }
        // 图片大小
        if( file.size / 1024 / 1024 > MaxSize ){
            message.error("图片大小超过限制");
            return false;
        }
    }

    ImgTestPromise(base64){
        return new Promise(function (reslove,reject) {
            let Img = new Image();
            Img.src = base64;
            Img.onload = function(){
                if(  Img.width !== 0 && Img.height !== 0){
                    reslove();
                }else{
                    reject();
                }
            };
            Img.onerror = function () {   reject(); }
        })
    }

    FileBase64(img,callback){
        const f = new FileReader();
        f.addEventListener("load",function(){
            console.log(this.result);
            callback(this.result);
        });
        f.readAsDataURL(img)
    }

    fileChange({file,fileList,event}){
        !(function () {
            this.setState({fileList:fileList});
        }.bind(this))();

        if(file.status === "done"){
            fileList[0].url = this.qiniuhref + file.response.key;
            this.FileBase64(file.originFileObj,(base64)=>{
                this.ImgTestPromise(base64).then((res)=>{
                    this.setState({fileList:fileList});
                }).catch((err)=>{
                    message.error("当前图片格式错误，请检查图片格式");
                    this.setState({fileList:[]})
                });
            });
        }else if(file.status == "error"){
            message.error(file.error);
        }
    }

    accept = ".jpg,.png,.gif,.jpeg,.bmp";

    uploadPlugin = {
        action:"http://up-z2.qiniu.com",
        beforeUpload:this.beforeUpload,
        accept:this.accept
    };

    uploadData(file){
        const token = this.state.token;
        if(!token) { message.error("上传参数错误"); return;}
        const date = new Date().getTime();
        return {file:file,token:this.state.token,key:`moneyInfo_${date}`}
    }

    render() {
        const {fileList,alarm} = this.state;

        console.log(fileList);
        return (
            <Modal
                className="modal_gre-title"
                visible={!this.state.displayflag}
                title="打款信息核对"
                onCancel={this.handleCancel.bind(this, this.state.displayflag)}
                onOk={this.handleConfirm.bind(this, this.state.displayflag)}
            >
                <div className="clear">
                    <div className="settle_set_up clear">
                        <p className="settle_set_loadp">结算金额：<span>{this.props._amount}</span>元</p>
                        <p className="settle_set_loadp">还款金额：<span>{parseFloat(this.props._principal)+parseFloat(this.props._interest)}</span>元（包含本金 <span>{this.props._principal}</span>元、利息 <span>{this.props._interest}</span>元）</p>
                        <div className="settle_set_input">
                            <Upload
                                {...this.uploadPlugin}
                                data={this.uploadData}
                                fileList={fileList}
                                onChange={this.fileChange}
                                onRemove={this.fileRemove}
                            >
                                {
                                    fileList.length < 1 &&
                                    <Button type="primary" ghost  icon="upload">上传汇款凭证</Button>
                                }
                            </Upload>
                            {
                                alarm &&
                                <p className="operLog_auditAlarm">
                                    请上传8M以内的BMP、JPEG、JPG、GIF、PNG格式的文件
                                </p>
                            }
                        </div>
                    </div>
                </div>
            </Modal>
        )
    }
}